package com.mall.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.admin.interfaces.Permission;
import com.mall.commondataformat.R;
import com.mall.commonutils.OssUtil;
import com.mall.dingdan.entity.Dingdan;
import com.mall.dingdan.service.DingdanService;
import com.mall.inform.entity.Inform;
import com.mall.inform.service.InformService;
import com.mall.product.entity.Product;
import com.mall.product.service.ProductService;
import com.mall.user.entity.User;
import com.mall.user.service.UserService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import static com.mall.commonutils.ResultCode.PAGE_LIMIT;

/**
 * @description 核心业务功能模块
 * @author Riskre
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private UserService userService;

    @Autowired
    private InformService informService;

    @Autowired
    private ProductService productService;

    @Autowired
    private DingdanService dingdanService;

    //删除用户
    @Permission
    @ApiOperation("删除用户")
    @PostMapping("/deleteUser")
    public R deleteUser(int id) {
//        User user = (User) session.getAttribute(USER_IN_SESSION);
//
//        if (user != null){
//            int role = user.getRole();
//            if (role == 1){
//
//                return R.error().message("无管理员权限");
//            }
//        }else {
//            return R.error().message("无管理员权限");
//        }

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        boolean res = userService.remove(wrapper);
        if (res) {
            return R.ok();
        } else {
            return R.error().message("删除用户失败");
        }
    }

    //查询所有用户
    @Permission
    @ApiOperation("查询所有用户")
    @GetMapping("/getUserList/{page}")
    public R getUserList(@ApiParam(name = "page", value = "当前页码", required = true)
                         @PathVariable Integer page) {

//        User user = (User) session.getAttribute(USER_IN_SESSION);
//
//        if (user != null){
//            int role = user.getRole();
//            if (role == 1){
//
//                return R.error().message("无管理员权限");
//            }
//        }else {
//            return R.error().message("无管理员权限");
//        }

        Page<User> userPage = new Page<>(page, PAGE_LIMIT);

        QueryWrapper<User> wrapper = new QueryWrapper<>();

        userService.page(userPage, wrapper);

        List<User> userList = userPage.getRecords();

        if (userList == null) {
            return R.error().message("未查询到用户");
        }
        return R.ok().data("userList", userList);
    }

    //修改用户
    @Permission
    @ApiOperation("修改用户")
    @PostMapping("/updateUser")
    public R updateUser(int id, String username, int gender, int age, String phone, double money) {

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        User user = userService.getOne(wrapper);

        user.setUsername(username);
        user.setGender(gender);
        user.setAge(age);
        user.setPhone(phone);
        user.setMoney(money);

        boolean res = userService.updateById(user);
        if (res) {
            return R.ok().message("修改成功");
        } else {
            return R.error().message("修改失败");
        }

    }

    //修改用户权限
    @Permission
    @ApiOperation("修改用户权限")
    @PostMapping("/changeUserRole")
    public R changeUserRole(int id, int role) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        User user = userService.getOne(wrapper);

        user.setRole(role);

        boolean res = userService.updateById(user);
        if (res) {
            return R.ok().message("修改成功");
        } else {
            return R.error().message("修改失败");
        }
    }

    //查询所有商品
    @Permission
    @ApiOperation("查询所有商品")
    @GetMapping("/getProductList/{page}")
    public R getProductList(@ApiParam(name = "page", value = "当前页码", required = true)
                            @PathVariable Integer page) {
        Page<Product> productPage = new Page<>(page, PAGE_LIMIT);
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        productService.page(productPage, wrapper);
        List<Product> productList = productPage.getRecords();

        if (productList == null) {
            return R.error().message("未查询到商品");
        }
        return R.ok().data("productList", productList);
    }

    //添加商品
    @Permission
    @ApiOperation("添加商品")
    @PostMapping("/addProduct")
    public R addProduct(String name, String intro, double price, int count, String picture, String address) {
//        User user = (User) session.getAttribute(USER_IN_SESSION);
//
//        if (user != null){
//            int role = user.getRole();
//            if (role == 1){
//
//                return R.error().message("无管理员权限");
//            }
//        }else {
//            return R.error().message("无管理员权限");
//        }
        Product product = new Product();
        //添加商品所有字段
        product.setName(name);
        product.setIntro(intro);
        product.setPrice(price);
        product.setCount(count);
        product.setPicture(picture);
        product.setAddress(address);

        boolean res = productService.save(product);
        if (res) {
            return R.ok();
        } else {
            return R.error().message("添加商品失败");
        }

    }

    //修改商品
    @Permission
    @ApiOperation("修改商品")
    @PostMapping("/updateProduct")
    public R updateProduct(int id, String name, String intro, double price, int count, String picture, String address) {
        //        User user = (User) session.getAttribute(USER_IN_SESSION);
//
//        if (user != null){
//            int role = user.getRole();
//            if (role == 1){
//
//                return R.error().message("无管理员权限");
//            }
//        }else {
//            return R.error().message("无管理员权限");
//        }
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        Product product = productService.getOne(wrapper);
        //添加修改姓名
        product.setName(name);
        product.setIntro(intro);
        product.setAddress(address);
        product.setPrice(price);
        product.setCount(count);
        product.setPicture(picture);

        boolean res = productService.updateById(product);
        if (res) {
            return R.ok().message("修改成功");
        } else {
            return R.error().message("修改失败");
        }
    }

    //删除商品
    @Permission
    @ApiOperation("删除商品")
    @PostMapping("/deleteProduct")
    public R deleteProduct(int id) {
        //        User user = (User) session.getAttribute(USER_IN_SESSION);
//
//        if (user != null){
//            int role = user.getRole();
//            if (role == 1){
//
//                return R.error().message("无管理员权限");
//            }
//        }else {
//            return R.error().message("无管理员权限");
//        }

        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        boolean res = productService.remove(wrapper);
        if (res) {
            return R.ok();
        } else {
            return R.error().message("删除商品失败");
        }

    }

    //查询所有订单
    @Permission
    @ApiOperation("查询所有订单")
    @GetMapping("/getOrderList/{page}")
    public R getOrderList(@ApiParam(name = "page", value = "当前页码", required = true)
                          @PathVariable Integer page) {
        Page<Dingdan> dingdanPage = new Page<>(page, PAGE_LIMIT);

        QueryWrapper<Dingdan> wrapper = new QueryWrapper<>();

        dingdanService.page(dingdanPage, wrapper);

        List<Dingdan> dingdanList = dingdanPage.getRecords();
        if (dingdanList == null) {
            return R.error().message("未查询到订单");
        }
        return R.ok().data("dingdanList", dingdanList);
    }

    //删除订单
    @Permission
    @ApiOperation("删除订单")
    @PostMapping("/deleteOrder")
    public R deleteOrder(int id) {

        QueryWrapper<Dingdan> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        boolean res = dingdanService.remove(wrapper);
        if (res) {
            return R.ok();
        } else {
            return R.error().message("删除订单失败");
        }

    }

    //确认发货
    @Permission
    @ApiOperation("确认发货")
    @PostMapping("/sendProduct")
    public R sendProduct(int id, int isSend) {
        QueryWrapper<Dingdan> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        Dingdan dingdan = dingdanService.getOne(wrapper);
        if (dingdan.getIsAccept() == 0 && dingdan.getIsPay() == 1) { //已支付，未收到货，才可确认发货
            dingdan.setIsSend(isSend);
        } else {
            return R.error().message("确认发货失败");
        }
        boolean res = dingdanService.updateById(dingdan);
        if (res) {
            return R.ok().message("确认发货成功");
        } else {
            return R.error().message("确认发货失败");
        }

    }

    //发布公告
    @Permission
    @ApiOperation("发布公告")
    @PostMapping("/putInform")
    public R putInform(String content) {
        //        User user = (User) session.getAttribute(USER_IN_SESSION);
//
//        if (user != null){
//            int role = user.getRole();
//            if (role == 1){
//
//                return R.error().message("无管理员权限");
//            }
//        }else {
//            return R.error().message("无管理员权限");
//        }
        Inform inform = new Inform();
        inform.setContent(content);

        if (inform == null) {
            return R.error().message("发布失败");
        }
        boolean res = informService.save(inform);
        if (res) {
            return R.ok().message("发布成功");
        } else {
            return R.error().message("发布失败");
        }
    }

    //获取所有公告
    @Permission
    @ApiOperation("获取所有公告")
    @GetMapping("/getInformList/{page}")
    public R getInformList(@ApiParam(name = "page", value = "当前页码", required = true)
                           @PathVariable Integer page) {
        Page<Inform> informPage = new Page<>(page, PAGE_LIMIT);

        QueryWrapper<Inform> wrapper = new QueryWrapper<>();

        informService.page(informPage, wrapper);
        List<Inform> informList = informPage.getRecords();
        if (informList == null) {
            return R.error().message("未获取到公告");
        }
        return R.ok().data("informList", informList);
    }

    @Permission
    @ApiOperation("上传图片返回图片url")
    @PostMapping("/getImgUrl")
    public R getImgUrl(MultipartFile file) {
        String uploadUrl = null;
        OssUtil ossUtil=new OssUtil();
        try {
            if (file != null) {
                String filename = file.getOriginalFilename();
                if (!"".equals(filename.trim())) {
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);
                    //上传到OSS
                    uploadUrl = ossUtil.upload(newFile);
                    newFile.delete();//删除保存在本地的文件，若需要保存在本地则注释掉
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(uploadUrl==null){
            return R.error().message("生成url失败");
        }else{
            String OssUrl=ossUtil.getUrl(uploadUrl);
            return R.ok().data("OssUrl",OssUrl);
        }

    }

}
